package com.yicong.ants.manager;

import android.app.Activity;
import android.net.Uri;

import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.x.livesdk.LiveActivity;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.ui.circle.article.ArticleWebActivity;
import com.yicong.ants.ui.coin.TransActivity;
import com.yicong.ants.ui.coin.UserCoinActivity;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.ui.hotel.HotelActivity;
import com.yicong.ants.ui.me.UserInfoActivity;
import com.yicong.ants.ui.me.recommend.MyTeamActivity;
import com.yicong.ants.ui.me.recommend.ShareActivity;
import com.yicong.ants.ui.other.FragmentContainerActivity;
import com.yicong.ants.ui.present.TaskCenterActivity;
import com.yicong.ants.ui.scenic.ScenicDetailConfigActivity;
import com.yicong.ants.ui.scenic.ScenicListActivity;
import com.yicong.ants.ui.video.VideoProfileActivity;
import com.yicong.ants.ui.video.VideoSharedActivity;

import java.net.URLDecoder;

import kotlin.text.Charsets;

/**
 * @author cch
 * @version 2020/12/29
 */
public class RouterHelper {

    /**
     * 路由
     *
     * @param url link
     * @return 是否路由成功
     */
    public static boolean router(Activity context, String url) {
        if (StringHelper.isEmpty(url)) {
            return false;
        }
        Logs.logEvent("RouterHelper.router " + url);

        // ants://platform/app?id=11040&uid=1023456
        if (tryRoutePlatformUri(context, url)) {
            return true;
        }

        // 常见问题
        if (url.contains("/api/v2/block/faq")) {
            Router.turnTo(context, YcWebViewActivity.class)
                    .putExtra(Const.Extra.Web_View_Url, url)
                    .putExtra(Const.Extra.Web_View_Tile, "常见问题")
                    .start();
            return true;
        }

        // 领导人分享
        if (url.contains("/api/v2/block/starShare")) {
            Router.turnTo(context, FragmentContainerActivity.class)
                    .putExtra(Constants.Extra.Fragment, Constants.Container.StarShare)
                    .putExtra(Constants.Extra.Title, "领导人分享")
                    .start();
            return true;
        }

        // 社区文章页
        if (url.contains(".com/block/#/")) {
            Router.turnTo(context, ArticleWebActivity.class)
                    .putExtra(Constants.Extra.Id, UrlUtil.getValueFromUrl(url, "office_id"))
                    .putExtra(Const.Extra.Web_View_Url, url)
                    .start();
            return true;
        }

        // app 拦截url
        if (url.contains("/api/v2/web/apps")) {
            switch (UrlUtil.getValueFromUrl(url, "type")) {
                case "login":
                    UserManager.routeLogin(context);
                    return true;
                case "user_center":
                    RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                    return true;
            }
        }
        if (url.contains("/#/room")) {
            String liveNumber = UrlUtil.getValueFromUrl(url, "live_number");
            if (!UserManager.isLogin()) {
                UserManager.routeLogin(context);
                return true;
            }
            LiveActivity.Companion.start(context, liveNumber, true);
            return true;
        }
        if (!url.startsWith("http")) {
            return false;
        }

        // 尝试从 链接里 拿title
        String title = UrlUtil.getValueFromUrl(url, "title");
        if (StringHelper.isEmpty(title)) {
            title = UiHelper.getString(R.string.app_name);
        }
        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, url)
                .putExtra(Const.Extra.Web_View_Tile, title)
                .putExtra(Constants.Extra.Yc_Web_View_Can_Share, true)
                .start();
        return false;
    }

    /**
     * 是否是蚁丛链接
     */
    public static boolean isAntsLink(String content) {
        if (StringHelper.isEmpty(content)) {
            return false;
        }

        if (content.contains("ants://") || content.contains("ants_link=1")) {
            return true;
        }
        return false;
    }

    /*
        以 ants:// 开头，或者包含  ants_link=1 都是蚁丛链接
        id=11010	打开任务中心
        id=11020	打开推荐好友
        id=11030	打开门票中心
        id=11040	打开转赠
        id=11050	打开个人中心
        id=11060	打开我的团队
        id=11060	短视频
        id=11081	景区相关
        id=12010	打开蚁丛商城
        id=12020	打开酒店
        id=12030	打开线路
    */
    public static boolean tryRoutePlatformUri(Activity context, String url) {
        try {
            Logs.logEvent("tryRoutePlatformUri " + url);
            String target = "";
            Uri uri = Uri.parse(url);
            if (!isAntsLink(url)) {
                return false;
            }
            String title = uri.getQueryParameter("title");
            if (StringHelper.isEmpty(title)) {
                title = UrlUtil.getValueFromUrl(url, "ants_title");
            }

            // 如果是 ants_link = 1
            if (url.contains("ants_link=1") && !url.contains("ants://")) {
                // 是否显示标题
                boolean showTitle = StringHelper.isNotEmpty(title);
                Router.turnTo(context, YcWebViewActivity.class)
                        .putExtra(Const.Extra.Web_View_Url, url)
                        .putExtra(Const.Extra.Web_View_Tile, String.valueOf(title))
                        .putExtra(Const.Extra.Web_View_Title_Visible, showTitle)
                        .checkLogin(true)
                        .start();
                return true;
            }

            String id = uri.getQueryParameter("id");
            String uid = uri.getQueryParameter("uid");
            String v = uri.getQueryParameter("v");

            if (StringHelper.isEmpty(id)
                    || !url.contains("platform/app")) {
                return false;
            }

            switch (id) {
                case "10000":
                    String link = UrlUtil.getValueFromUrl(url, "link");
                    String liveNumber = UrlUtil.getValueFromUrl(URLDecoder.decode(link, Charsets.UTF_8.displayName()), "live_number");
                    if (StringHelper.isNotEmpty(liveNumber)) {
                        if (!UserManager.isLogin()) {
                            UserManager.routeLogin(context);
                            return true;
                        }
                        LiveActivity.Companion.start(context, liveNumber, true);
                        return true;
                    }
                    Router.turnTo(context, YcWebViewActivity.class)
                            .putExtra(Const.Extra.Web_View_Url, URLDecoder.decode(UrlUtil.getValueFromUrl(url, "link")))
                            .putExtra(Const.Extra.Web_View_Tile, String.valueOf(title))
                            .putExtra(Const.Extra.Web_View_Title_Visible, StringHelper.isNotEmpty(title))
                            .checkLogin(true)
                            .start();
                    return true;
                case "11010":
                    ZzConfigs.routeAtyCheckLogin(context, TaskCenterActivity.class);
                    return true;
                case "11020":
                    ZzConfigs.routeAtyCheckLogin(context, ShareActivity.class);
                    return true;
                case "11030":
                    ZzConfigs.routeAtyCheckLogin(context, UserCoinActivity.class);
                    return true;
                case "11040":
                    Router.turnTo(context, TransActivity.class)
                            .checkLogin(true)
                            .putExtra(Constants.Extra.Uid, uid)
                            .start();
                    return true;
                case "11050":
                    ZzConfigs.routeAtyCheckLogin(context, UserInfoActivity.class);
                    return true;
                case "11060":
                    ZzConfigs.routeAtyCheckLogin(context, MyTeamActivity.class);
                    return true;
                case "11070":  // 短视频页
                    Router.turnTo(context, VideoSharedActivity.class)
                            .putExtra(Constants.Extra.Vid, uri.getQueryParameter("vid"))
                            .start();
                    return true;
                case "11080":
                    Router.turnTo(context, ScenicListActivity.class)
                            .putExtra(Constants.Extra.Scenic_Type, Constants.Scenic_Type.PartnerScenic)
                            .start();
                    return true;
                case "11081":
                    if (StringHelper.isEmpty(v)) {
                        return false;
                    }
                    Router.turnTo(context, ScenicDetailConfigActivity.class)
                            .putExtra(Constants.Extra.Id, v)
                            .start();
                    return true;
                case "11071":  // 短视频个人主页
                    RxBus.get().postEvent(Constants.Event.Main_Tab_Turn, 2);
                    Router.turnTo(context, VideoProfileActivity.class)
                            .putExtra(Constants.Extra.Uid, uid)
                            .putExtra(Constants.Utm.source, extractUtmSource(url))
                            .putExtra(Constants.Utm.content, extractUtmContent(url))
                            .start();
                    return true;
                case "12010": // 商城首页
                    target = appendUtmInfo(Constants.getWebUrl("mall"), url);
                    Router.turnTo(context, YcWebViewActivity.class)
                            .putExtra(Const.Extra.Web_View_Url, target)
                            .putExtra(Const.Extra.Web_View_Tile, "蚁丛商城")
                            .putExtra(Const.Extra.Web_View_Title_Visible, false)
                            .checkLogin(true)
                            .start();
                    return true;
                case "12020":
                    Router.turnTo(context, HotelActivity.class).start();
                    return true;
                case "12030":
                    ZzConfigs.toWebActivityByUrl(context, "travel_line");
                    return true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 提取 utm_source 值
     */
    public static String extractUtmSource(String url) {
        if (StringHelper.isEmpty(url)) {
            return "";
        }
        return StringHelper.null2Space(UrlUtil.getValueFromUrl(url, Constants.Utm.source));
    }

    public static String extractUtmContent(String url) {
        if (StringHelper.isEmpty(url)) {
            return "";
        }
        return StringHelper.null2Space(UrlUtil.getValueFromUrl(url, Constants.Utm.content));
    }

    /**
     * 拼接 utm 参数，如果有的话
     *
     * @param target    最终url
     * @param sourceUrl 来源url
     */
    public static String appendUtmInfo(String target, String sourceUrl) {
        if (StringHelper.isEmpty(sourceUrl)) {
            return target;
        }
        String source = extractUtmSource(sourceUrl);
        String content = extractUtmContent(sourceUrl);
        if (StringHelper.isNotEmpty(source)) {
            target = UrlUtil.appendParameterCompat(target, Constants.Utm.source, source);
        }
        if (StringHelper.isNotEmpty(content)) {
            target = UrlUtil.appendParameterCompat(target, Constants.Utm.content, content);
        }
        return target;
    }

    public static void toScenicDetail(Activity activity, String id) {
        String zzz = "/zzz/";
        String vue = "/#/";
        String url = Constants.getWebUrl("scenic_detail").replace(vue, zzz);
        url = UrlUtil.appendParameter(url, "scenic_id", id).replace(zzz, vue);
        Router.turnTo(activity, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, url)
                .putExtra(Const.Extra.Web_View_Title_Visible, false)
                .start();
    }
}
